//
//  IdiomListController.swift
//  XingCeHelper
//
//  Created by 申铭 on 2023/1/18.
//

import UIKit
import CoreData

class IdiomListController: BaseTableViewController {
    
    private var fetchedRC: NSFetchedResultsController<Idiom>!

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchedRC = IdiomStore.query()
        fetchedRC.delegate = self
        tableView.rowHeight = 50
        tableView.sectionHeaderHeight = 30
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
        
        let barBtn = UIBarButtonItem(title: "删除全部", style: .plain, target: self, action: #selector(deleteAll))
        barBtn.setTitleTextAttributes([NSAttributedString.Key.font : kNavBarBtnFont], for: .normal)
        navigationItem.rightBarButtonItem = barBtn
    }
    
    private func deleteIdiom(title: String) {
        let alert = UIAlertController(title: nil, message: "此操作将删除该成语的所有数据，是否确认删除？", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "删除", style: .destructive, handler: { _ in
            IdiomStore.delete(title: title)
        }))
        present(alert, animated: true, completion: nil)
    }
    
    @objc private func deleteAll() {
        let alert = UIAlertController(title: nil, message: "是否确认删除全部数据？", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "删除", style: .destructive, handler: { _ in
            IdiomStore.deleteAll()
        }))
        present(alert, animated: true, completion: nil)
    }
}

extension IdiomListController {
    /// 共多少组
    override func numberOfSections(in tableView: UITableView) -> Int {
        return fetchedRC.sections?.count ?? 0
    }
    
    /// 每组元素的数量
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fetchedRC.sections?[section].numberOfObjects ?? 0
    }
    
    /// 设置索引
    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return fetchedRC.sectionIndexTitles
    }
    
    /// 设置索引
    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return fetchedRC.section(forSectionIndexTitle: title, at: index)
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
        cell.textLabel?.text = fetchedRC.object(at: indexPath).title
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        super.tableView(tableView, didSelectRowAt: indexPath)
    }
    
    /// 组标题
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return fetchedRC.sections?[section].indexTitle ?? ""
    }
    
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = UIContextualAction(style: .destructive, title: "删除") { (action, view, completion) in
            if let title = self.fetchedRC.object(at: indexPath).title {
                self.deleteIdiom(title: title)
            }
            completion(false)
        }
            
        let config = UISwipeActionsConfiguration(actions: [delete])
        config.performsFirstActionWithFullSwipe = false
        return config
    }
}

/// 更新操作
extension IdiomListController: NSFetchedResultsControllerDelegate {
    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        self.tableView.beginUpdates()
    }
    
    /// 更新Cell
    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch type {
        case .insert:
            if let  indexPath = newIndexPath {
                tableView.insertRows(at: [indexPath], with: .automatic)
            }
        case .delete:
            if let  indexPath = indexPath {
                tableView.deleteRows(at: [indexPath], with: .automatic)
            }
        case .update:
            if let  indexPath = indexPath {
                let cell = tableView.cellForRow(at: indexPath)
                cell?.textLabel?.text = fetchedRC.object(at: indexPath).title
            }
        case .move:
            if let indexPath = indexPath {
                tableView.deleteRows(at: [indexPath], with: .automatic)
            }
            if let newIndexPath = newIndexPath {
                tableView.insertRows(at: [newIndexPath], with: .automatic)
            }
        @unknown default: break
        }
    }
    
    /// 更新分组
    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
        switch type {
        case .insert, .update, .move: break;
        case .delete:
            var indexSet = IndexSet()
            indexSet.insert(sectionIndex)
            tableView.deleteSections(indexSet, with: .automatic)
        @unknown default: break
        }
    }
    
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.endUpdates()
    }
}
